package com.wefans.wefansapp.activity;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.data.ResDefaultData;
import com.wefans.wefansapp.common.tool.data.ResStarAllData;
import com.wefans.wefansapp.common.tool.data.StarData;
import com.wefans.wefansapp.common.tool.data.StarGroupData;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;
import com.wefans.wefansapp.common.tool.popup.MemberJoinDialog;
import com.wefans.wefansapp.common.tool.utils.MFToastUtil;

public class MystarActivity extends BaseActivity {

	private Context mContext = null;
	private Button mBtnSave = null;
	
	private String mStrEmail = "";
	private String mStrName = "";
	private String mStrNickname = "";
	private String mStrPassword = "";
	private String mStrCountry = "";
	private String mStrPhoneNum = "";
	private String mStrRecommender = "";
	
	boolean bFromJoin = false;
	
	private int nSelectIdx = -1;	
	private TextView[] tvSelectArray =  new TextView[5];
	
	private Button[] mBtnTabArray =  new Button[5];
	
	private ListView mLvSolo = null;
	private MystarAdapter mAdtSolo = null;
	private ExpandableListView mLvGropu = null;
	private MystarGroupAdapter mAdtGroup = null;
	
	private ArrayList<StarGroupData> mGroupList = new ArrayList<StarGroupData>();
	private ArrayList<StarData> mSoloList = new ArrayList<StarData>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		mContext = this;
		
		setContentView(R.layout.activity_mystar);
		
		Intent intent = getIntent();
		
		if (intent != null) {
			mStrCountry = intent.getStringExtra("country");
			mStrName = intent.getStringExtra("name");
			mStrNickname = intent.getStringExtra("nickname");
			mStrEmail = intent.getStringExtra("email");
			mStrPassword = intent.getStringExtra("passwd");
			mStrPhoneNum = intent.getStringExtra("mobile");
			mStrRecommender = intent.getStringExtra("recommend");
			
			String strFrom = intent.getStringExtra("from");
			if ("join".equals(strFrom)) {
				bFromJoin = true;
			}
		}
		
		tvSelectArray[0] = (TextView)findViewById(R.id.TV_SELECT1);
		tvSelectArray[1] = (TextView)findViewById(R.id.TV_SELECT2);
		tvSelectArray[2] = (TextView)findViewById(R.id.TV_SELECT3);
		tvSelectArray[3] = (TextView)findViewById(R.id.TV_SELECT4);
		tvSelectArray[4] = (TextView)findViewById(R.id.TV_SELECT5);
		
		mBtnTabArray[0] = (Button)findViewById(R.id.BTN_GROUP_MAN);
		mBtnTabArray[1] = (Button)findViewById(R.id.BTN_GROUP_WOMEN);
		mBtnTabArray[2] = (Button)findViewById(R.id.BTN_SOLO_MAN);
		mBtnTabArray[3] = (Button)findViewById(R.id.BTN_SOLO_WOMAN);
		mBtnTabArray[4] = (Button)findViewById(R.id.BTN_GROUP_HYBRID);
		
		mLvSolo = (ListView)findViewById(R.id.LV_SOLO);
		mLvGropu = (ExpandableListView)findViewById(R.id.LV_GROUP);
		mBtnSave = (Button) findViewById(R.id.BTN_SAVE);
		
		setDummyData();
		
		mAdtSolo = new MystarAdapter(mContext, mSoloList, mFavoriteListener);
		mLvSolo.setAdapter(mAdtSolo);
		
		mAdtGroup = new MystarGroupAdapter(mContext, mGroupList, mFavoriteListener);
		mLvGropu.setAdapter(mAdtGroup);
		
		tvSelectArray[0].setOnClickListener(this);
		tvSelectArray[1].setOnClickListener(this);
		tvSelectArray[2].setOnClickListener(this);
		tvSelectArray[3].setOnClickListener(this);
		tvSelectArray[4].setOnClickListener(this);
		
		mBtnTabArray[0].setOnClickListener(this);
		mBtnTabArray[1].setOnClickListener(this);
		mBtnTabArray[2].setOnClickListener(this);
		mBtnTabArray[3].setOnClickListener(this);
		mBtnTabArray[4].setOnClickListener(this);
		
		mBtnSave.setOnClickListener(this);
		
		requestAllStarData();
	}
	
	private void requestAllStarData() {
		
		String strUrl = MFNetworkManager.BASE_URL + "/star/get_all.php";
		strUrl = strUrl + "?mem_idx=" + MFDataManager.getInstance(getApplicationContext()).getMebmerIdx();
		MFNetworkManager.getInstance(this).requestGetData(MFNetworkManager.REQUEST_ALLSTAR_INFO, strUrl, mNetworkListener);
	}
	
	private void requestMemberJoin() {
		String strUrl = MFNetworkManager.BASE_URL + "/user/set_regist.php";
		
		Hashtable<String, String> body = new Hashtable<String, String>();
		body.put("country", "KOR");
		body.put("name", mStrName);
		body.put("nickname", mStrNickname);
		body.put("passwd", mStrPassword);  
		body.put("email", mStrEmail);
		body.put("mobile", mStrPhoneNum);
		body.put("recommend", mStrRecommender);
		
		MFNetworkManager.getInstance(this).requestPostData(MFNetworkManager.REQUEST_JOIN_MEMBER, strUrl, body, mNetworkListener);
	}
	
	IOnNetworkListener mNetworkListener = new IOnNetworkListener() {
		
		@Override
		public void onNetMessage(int resultCode, NetMessage message) {
			try {
	            //서버 여동 데이터
	            if( message instanceof NetJsonData ) {
	                long magicNum = ((NetJsonData) message).getMagicNum();
	                String json = ((NetJsonData) message).getResponseJson();
	                
	                if( json == null ) {
	                    throw new Exception("invalid json data");
	                }
	                
	                Gson gson = new Gson();
	                
	                if (magicNum == MFNetworkManager.REQUEST_ALLSTAR_INFO) {
	                	
	                	ResStarAllData resultData = (ResStarAllData)gson.fromJson(json, ResStarAllData.class);
	                    if( resultData == null ) {
	                        throw new Exception("Gson parsing error");
	                    }
	                	
//	                	if (resultData.isSuccsess()) {
//	                	}
	                } else if (magicNum == MFNetworkManager.REQUEST_JOIN_MEMBER) {
	                	ResDefaultData resultData = (ResDefaultData)gson.fromJson(json, ResDefaultData.class);
	                	if (resultData.isSuccsess()) {
	                		MemberJoinDialog dialog = new MemberJoinDialog(mContext, null);
	            			
	            			dialog.setOnDismissListener(new OnDismissListener() {
	            				
	            				@Override
	            				public void onDismiss(DialogInterface dialog) {
	            					setResult(Activity.RESULT_OK);
	            					finish();
	            				}
	            			});
	            			dialog.show();
		                } else {
		                	MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
		                }
	                }
	            }	            
	        } catch(Exception e) {
	            MFDebug.e(e);
	        }		
		}
	};
	
	private MystarFavoriteListener mFavoriteListener = new MystarFavoriteListener() {
		
		@Override
		public void onFavoriteChange(String strId, String strName, boolean bFavorite) {
			if (bFavorite) {
				TextView tvSelect = getEmptySelect();
				tvSelect.setText(strName);
				tvSelect.setTag(strId);
				tvSelect.setBackgroundResource(R.drawable.mystar_blue);
			} else {
				for (int i = 0; i < tvSelectArray.length; i++) {
					TextView tvTemp = tvSelectArray[i];
					
					if (tvTemp.getTag() == strId) {
						tvTemp.setText("");
						tvTemp.setTag(null);
						tvTemp.setBackgroundResource(R.drawable.mystar_select);
						if (nSelectIdx == i) {
							nSelectIdx = -1;
						}
					}
				}
			}
		}
	}; 
	
	private void setDummyData() {
		mGroupList = new ArrayList<StarGroupData>();
		
		StarGroupData group = new StarGroupData();
		group.setStrName("2PM");
		
		StarData child = new StarData();
		child.setStrId("01");
		child.setStrName("그룹전체");
		group.getChildList().add(child);
		child = new StarData();
		child.setStrId("02");
		child.setStrName("닌쿤");
		group.getChildList().add(child);
		child = new StarData();;
		child.setStrId("03");
		child.setStrName("우영");
		group.getChildList().add(child);
		mGroupList.add(group);
		
		group = new StarGroupData();
		group.setStrName("2AM");
		
		child = new StarData();
		child.setStrId("04");
		child.setStrName("그룹전체");
		group.getChildList().add(child);
		child = new StarData();
		child.setStrId("05");
		child.setStrName("준호");
		group.getChildList().add(child);
		child = new StarData();
		child.setStrId("06");
		child.setStrName("Jn K");
		group.getChildList().add(child);
		child = new StarData();
		child.setStrId("07");
		child.setStrName("우영");
		group.getChildList().add(child);
		mGroupList.add(group);
		
		StarData dtStar = new StarData();
		dtStar.setStrId("14");
		dtStar.setStrName("이승기");
		mSoloList.add(dtStar);
		dtStar = new StarData();
		dtStar.setStrId("15");
		dtStar.setStrName("JYP");
		mSoloList.add(dtStar);
		dtStar = new StarData();
		dtStar.setStrId("16");
		dtStar.setStrName("아이유");
		mSoloList.add(dtStar);
	}
	
	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.BTN_SAVE:
			if (bFromJoin) {
				requestMemberJoin();
			}
			break;
		case R.id.TV_SELECT1:
			clickSelect(0);
			break;
		case R.id.TV_SELECT2:
			clickSelect(1);
			break;
		case R.id.TV_SELECT3:
			clickSelect(2);
			break;
		case R.id.TV_SELECT4:
			clickSelect(3);
			break;
		case R.id.TV_SELECT5:
			clickSelect(4);
			break;
		case R.id.BTN_GROUP_MAN:
			updateByTab(0);
			break;
		case R.id.BTN_GROUP_WOMEN:
			updateByTab(1);
			break;
		case R.id.BTN_SOLO_MAN:
			updateByTab(2);
			break;
		case R.id.BTN_SOLO_WOMAN:
			updateByTab(3);
			break;
		case R.id.BTN_GROUP_HYBRID:
			updateByTab(4);
			break;
		}
		super.onClick(v);
	}
	
	private void updateByTab(int nTabIdx) {
		
		for (int i = 0; i < mBtnTabArray.length; i++) {
			mBtnTabArray[i].setSelected(i == nTabIdx ? true : false);
		}
		
		switch (nTabIdx) {
		case 0:
		case 1:
		case 4:
			mLvSolo.setVisibility(View.GONE);
			mLvGropu.setVisibility(View.VISIBLE);
			break;
		case 2:
		case 3:
			mLvSolo.setVisibility(View.VISIBLE);
			mLvGropu.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}
	
	private void clickSelect(int nIdx) {
		
		if (tvSelectArray[nIdx].getText().toString().length() <= 0)
			return;
		
		if (nIdx == nSelectIdx) {
			tvSelectArray[nIdx].setText("");
			tvSelectArray[nIdx].setTag(null);
			tvSelectArray[nIdx].setBackgroundResource(R.drawable.mystar_select);
			nSelectIdx = -1;
		} else {
			if (nSelectIdx >= 0) {
				tvSelectArray[nSelectIdx].setBackgroundResource(R.drawable.mystar_blue);
			}
			tvSelectArray[nIdx].setBackgroundResource(R.drawable.mystar_black);
			nSelectIdx = nIdx;
		}
	}
	
	private TextView getEmptySelect() {
		
		TextView tvSelect = null;
		
		String strTemp = "";
		
		for (int i = 0; i < tvSelectArray.length; i++) {
			tvSelect = tvSelectArray[i];
			strTemp = tvSelect.getText().toString();
			
			if (strTemp == null || strTemp.length() == 0) {
				break;
			}
		}
		
		return tvSelect;
	}
}
